from flask import Flask, render_template, Response, jsonify,request
from flask_socketio import SocketIO, emit
import io
import time
from threading import Condition
import logging
from base_ctrl import BaseController
import asyncio
# from aiortc import RTCPeerConnection, RTCSessionDescription, VideoStreamTrack
import uuid
# from cv_ctrl import OpencvFuncs
# from av import VideoFrame

app = Flask(__name__)
socketio = SocketIO(app)
# log = logging.getLogger('werkzeug')
# log.setLevel(logging.ERROR)
# app.debug = True # 开关终端日志
# active_pcs = {}
# MAX_CONNECTIONS = 1
# pcs = set()

base = BaseController('/dev/serial0', 115200)

# ----------------- 数据接口,读取数据 [未开始] -----------------
@app.route('/data')
def data():
    # 这里只是 mock，真实可接传感器
    import random
    return jsonify({           # jsonify 函数用于将 Python 对象转换为 JSON 响应对象
        'temperature': round(random.uniform(20, 35), 1),
        'speed': random.randint(0, 100),
        'time': time.strftime('%H:%M:%S')
    })


# ----------------- 设备接口 -----------------
# @app.route('/device/<dev>/<action>')
# def device(dev, action):
#     try:
#         if dev == 'buzzer':
#             if action == 'on':
#                 print('[ Info ] buzzer on')
#                 # 发送蜂鸣器开启命令
#                 base.send_command({"T": 2, "status": 1})
#             elif action == 'off':
#                 print('[ Info ] buzzer off')
#                 # 发送蜂鸣器关闭命令
#                 base.send_command({"T": 2, "status": 0})
#         elif dev == 'light':
#             if action == 'on':
#                 print('[ Info ] light on')
#                 # 发送灯开启命令
#                 base.send_command({"T": 3, "status": 1})
#             elif action == 'off':
#                 print('[ Info ] light off')
#                 # 发送灯关闭命令
#                 base.send_command({"T": 3, "status": 0})
#         return jsonify({"status": "success", "message": f"{dev} {action} command sent"})
#     except Exception as e:
#         print(f"[ Error ] Device control error: {e}")
#         return jsonify({"status": "error", "message": str(e)}), 500

# ----------------- 控制接口 -----------------
# websocket 控制
@socketio.on('json', namespace='/move')
def handle_socket_json(json):
    try:
        # ---------- 测试代码 ---------- # 
        # print(f"[ 接收到控制命令 ]: {json}")
        
        # # 检查命令类型并执行相应操作
        # if isinstance(json, dict) and 'T' in json:
        #     if json['T'] == 1:  # 运动控制
        #         print("[ 执行运动控制 ]")
        #         # 打印左右轮速度
        #         if 'L' in json and 'R' in json:
        #             print(f"左轮速度: {json['L']}, 右轮速度: {json['R']}")
        #     elif json['T'] == 2:  # 蜂鸣器控制
        #         print("[ 执行蜂鸣器控制 ]")
        #     elif json['T'] == 3:  # 灯光控制
        #         print("[ 执行灯光控制 ]")
        # ------------------------------- #
        # 执行控制命令
        base.base_json_ctrl(json)
        print("[ 控制命令执行完成 ]")
    except Exception as e:
        print(f"[ 错误 ] 处理JSON数据时出错: {e}")

# -------------- 视频流控制 -------------- #
# class CameraStreamTrack(VideoStreamTrack):
#     def __init__(self):
#         super().__init__()
#         self.cvf = OpencvFuncs()

#     async def recv(self):
#         pts, time_base = await self.next_timestamp()
#         frame = self.cvf.frame_process()
#         # 如果 frame 是 JPEG 字节流，需解码为 numpy 数组
#         video_frame = VideoFrame.from_ndarray(frame, format="bgr24")
#         video_frame.pts = pts
#         video_frame.time_base = time_base
#         return video_frame
# @app.route('/offer', methods=['POST'])
# def offer():
#     params = request.json
#     offer = RTCSessionDescription(sdp=params["sdp"], type=params["type"])
#     pc = RTCPeerConnection()
#     pcs.add(pc)

#     # 添加视频轨道
#     pc.addTrack(CameraStreamTrack())

#     async def process_offer():
#         await pc.setRemoteDescription(offer)
#         answer = await pc.createAnswer()
#         await pc.setLocalDescription(answer)
#         return jsonify({
#             "sdp": pc.localDescription.sdp,
#             "type": pc.localDescription.type
#         })

#     # 用 asyncio 运行协程
#     loop = asyncio.new_event_loop()
#     asyncio.set_event_loop(loop)
#     result = loop.run_until_complete(process_offer())
#     return result

# ----------------- 主页 ----------------- #
@app.route('/')
def index():
    return render_template('index.html')



# ----------------- 主入口 -----------------
if __name__ == '__main__':
    # 启动摄像头线程

    try:
        app.run(host='0.0.0.0', port=5000, threaded=True)
    finally:
        print('[ Info ] Server stopped')